package com.ndood.core.social.qq.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.UserIdSource;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.security.AuthenticationNameUserIdSource;

import com.ndood.core.properties.QQProperties;
import com.ndood.core.properties.SecurityProperties;
import com.ndood.core.social.SocialAutoConfigurerAdapter;
import com.ndood.core.social.SocialConfig;
import com.ndood.core.social.qq.connect.QQConnectionFactory;

/**
 * 添加QQ Social自动配置类  qqConfig: qq
 * 只有配置了appid，该配置才生效
 */
@Configuration
@ConditionalOnProperty(prefix = "ndood.security.social.qq", name = "app-id")
public class QQAutoConfig extends SocialAutoConfigurerAdapter {

	@Autowired
	private SecurityProperties securityProperties;
	
	@Autowired
	private SocialConfig socialConfig;
	
	/**
	 * 创建ConnectionFactory
	 */
	@Override
	protected ConnectionFactory<?> createConnectionFactory() {
		QQProperties qqConfig = securityProperties.getSocial().getQq();
		return new QQConnectionFactory(qqConfig.getProviderId(), qqConfig.getAppId(), qqConfig.getAppSecret());
	}

	/**
	 * 获取社交登录用户连接
	 */
	@Override
	public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
		return socialConfig.getUsersConnectionRepository(connectionFactoryLocator);
	}
	
	/**
	 * One configuration class must implement getUserIdSource from SocialConfigurer.
	 * https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.social.UserIdSource
	 */
	@Override
	public UserIdSource getUserIdSource() {
		return new AuthenticationNameUserIdSource();
	}
	
}